<template>
  <a-modal :title="title" :width="800" v-model:visible="visible" @ok="onSubmit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-row>
        <a-col v-for="(i, idx) in appform" :key="idx + 'b'" :span="16">
          <a-form-item v-if="i.show" :label="i.label" :name="i.name">
            <a-input v-if="i.type === 'input' && i.name !== 'secret'" v-model:value="i.value" @change="valueChange" />
            <a-radio-group v-if="i.type === 'radio'" v-model:value="i.value" button-style="solid">
              <a-radio-button v-for="(e, num) in i.options" :value="e.value">{{ e.label }}</a-radio-button>
            </a-radio-group>
            <a-select
              v-if="i.type === 'select'"
              v-model:value="i.value"
              :mode="i.mode || ''"
              @change="selectChange(i)"
              :options="i.options"
            ></a-select>
            <a-textarea v-if="i.type === 'textarea'" v-model:value="i.value" :auto-size="{ minRows: 2, maxRows: 5 }" @change="valueChange" />
            <a-switch v-if="i.type === 'switch'" v-model:checked="i.value" :checkedValue="1" :unCheckedValue="0">
              <template #checkedChildren><check-outlined /></template>
              <template #unCheckedChildren><close-outlined /></template>
            </a-switch>
            <a-input suffix="天" v-if="i.type === 'inputtian'" v-model:value="i.value" />
            <UploadImg v-if="i.type === 'img'" v-model:value="i.value"></UploadImg>
            <UploadFile v-if="i.type === 'upFile'" v-model:value="i.vsalue" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, nextTick, reactive, toRaw, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import _ from 'lodash';
import UploadImg from '/@/components/file/img.vue';
import UploadFile from '/@/components/file/uploadFile.vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { applicationManagementApi } from '/@/api/system/applicationManagement-api';
import { configureApi } from '../../../../api/system/configure-api.js';

// 基本信息form
const appform = ref([
  { label: '编码', name: 'id', value: '', type: 'input', options: [], disabled: false, show: true },
  {
    label: '数据源类型',
    name: 'sourceType',
    value: '',
    type: 'select',
    options: [
      { label: 'SCIM v2.0', value: 'SCIMV20' },
      { label: 'API', value: 'API' },
      { label: 'MSAD', value: 'MSAD' },
      { label: 'LDAP', value: 'LDAP' },
      { label: 'DATABASE', value: 'DB' },
    ],
    disabled: false,
    show: true,
  },
  { label: '同步服务', name: 'service', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '定时任务', name: 'scheduler', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: 'JDBC驱动', name: 'scheduler', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: '地址', name: 'providerUrl', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '账号', name: 'principal', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '凭证', name: 'credentials', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '间隔区间', name: 'syncStartTime', value: '', type: 'inputtian', options: [], disabled: false, show: false },
  { label: '用户基本DN', name: 'userBasedn', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: '用户过滤条件', name: 'userFilters', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: '组织基本DN', name: 'orgBasedn', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: '组织过滤条件', name: 'orgFilters', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: 'Active Directory域', name: 'msadDomain', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: 'SSL', name: 'sslSwitch', value: '', type: 'switch', options: [], disabled: false, show: true },
  { label: '证书路径', name: 'trustStore', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: '证书密钥', name: 'trustStorePassword', value: '', type: 'input', options: [], disabled: false, show: false },
  { label: '执行时间', name: 'resumeTime', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '挂起时间', name: 'suspendTime', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '状态', name: 'status', value: '', type: 'switch', options: [], disabled: false, show: true },
]);

const activeKey = ref(0);
// emit
const emit = defineEmits(['reload']);

// 组件ref
const formRef = ref();

const formDefault = {
  id: undefined,
};
let form = reactive({ ...formDefault });
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  protocol: [{ required: true, message: '请选择协议', trigger: 'change' }],
  adapter: [{ required: true, message: '请输入', trigger: 'blur' }],
};
// 是否展示抽屉
const visible = ref(false);
const formType = ref(null);
const title = ref('');

function showDrawer(rowData, index, type) {
  title.value = type;
  formType.value = index;
  if (index) {
    //添加
    onClose();
  } else {
    //编辑
    rowData.status = Number(rowData.status);
    rowData.sslSwitch = Number(rowData.sslSwitch);
    appform.value.forEach((i) => {
      i.value = rowData[i.name] || '';
    });
    Object.assign(form, rowData);
    selectChange(appform.value[1]);
  }
  appform.value.forEach((i) => {
    form[i.name] = i.value;
  });
  visible.value = true;
}

//添加之前清空
function onClose() {
  Object.assign(form, formDefault);
  appform.value.forEach((i) => {
    i.value = i.defaultValue || '';
  });
  visible.value = false;
}

const paramObj = {};

function valueChange() {
  Object.assign(paramObj);

  paramObj['switch_status'] = true;

  appform.value.forEach((i) => {
    if (i.name === 'select_authorizedGrantTypes' && i.value && i.value.length) {
      paramObj['authorizedGrantTypes'] = i.value.join(',');
    } else if (i.name === 'select_scope' && i.value && i.value.length) {
      paramObj['scope'] = i.value.join(',');
    } else {
      paramObj[i.name] = i.value;
    }
  });
  Object.assign(form, paramObj);
}

let list = [];
function selectChange(obj) {
  if (obj.name == 'sourceType') {
    if (list.length) {
      list.forEach((i) => {
        appform.value[i].show = false;
      });
    }
    if (obj.value == 'SCIMV20') {
      list = [];
    } else if (obj.value == 'API') {
      list = [8];
    } else if (obj.value == 'MSAD') {
      list = [9, 10, 11, 12, 13, 14];
    } else if (obj.value == 'LDAP') {
      list = [9, 10, 11, 12, 13];
    } else if (obj.value == 'DB') {
      list = [4, 8, 10, 12];
    }
    list.forEach((i) => {
      appform.value[i].show = true;
    });
  }
  valueChange();
}

async function onSubmit() {
  valueChange();

  formRef.value
    .validate()
    .then(async () => {
      // SmartLoading.show();
      try {
        let res;
        //1 新增  0编辑
        if (formType.value == 1) {
          res = await configureApi.addSynchronizers(paramObj);
        } else {
          res = await configureApi.synchronizersUpdate(paramObj);
        }

        message.success(`${form.id ? '修改' : '添加'}成功`);
        onClose();
        emit('reload');
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        // SmartLoading.hide();
      }
    })
    .catch((error) => {
      console.log('error', error);
      message.error('参数验证错误，请仔细填写表单数据!');
    });
}
onMounted(() => {});
defineExpose({
  showDrawer,
});
</script>
